﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Web.Script.Serialization;
using DAL;
using BLL;
using System.Drawing;

namespace IAATO
{
    public partial class ProgrammeManagement : System.Web.UI.Page
    {
    
        protected NavireService navireService;
        protected CreneauService creneauService;
        protected ProgrammeService programmeService;
        protected SiteService siteService;
        protected ActiviteService activiteService;

        protected const string siteIndefini = "Undefined place";
        protected const string activiteIndefinie = "Undefined activity";

        protected JavaScriptSerializer serializer;

        //bool shouldBeInEditingMode;

        protected void Page_Load(object sender, EventArgs e)
        {
            navireService = new NavireService(new NavireManager());
            creneauService = new CreneauService(new CreneauManager());
            programmeService = new ProgrammeService(new ProgrammeManager());
            siteService = new SiteService(new SiteManager(), new ActiviteManager(), new CreneauService(new CreneauManager()));
            activiteService = new ActiviteService(new ActiviteManager(), new SiteManager());

            if (!IsPostBack)
            {
                hdfIdNavire.Value = Request.QueryString["id"];
                int navireId;

                if (!int.TryParse(hdfIdNavire.Value, out navireId))
                {
                    Response.Redirect("~/Default.aspx");
                }
                else if (HttpContext.Current.User.IsInRole("Navire"))
                {
                    string navireUserName = HttpContext.Current.User.Identity.Name;
                    string[] splitUserName = navireUserName.Split('_');

                    if (navireId != int.Parse(splitUserName[splitUserName.Length - 1]))
                        hdfNavireEtranger.Value = "True";    
                }

                NAVIRE navire = navireService.getNavireById(navireId);
                    
                if (navire == null)
                    Response.Redirect("~/Default.aspx");
                else
                    lblNomNavire.Text = navire.NOM;
                
                calProgramme.SelectedDate = DateTime.Today;
                lblDateProgramme.Text = calProgramme.SelectedDate.ToString("dd/MM/yy");
                hdfJour.Value = calProgramme.SelectedDate.Day.ToString();
                hdfMois.Value = calProgramme.SelectedDate.Month.ToString();
                hdfAnnee.Value = calProgramme.SelectedDate.Year.ToString();

                setProgramme();

                //shouldBeInEditingMode = false;
                //setEditingMode(shouldBeInEditingMode);

                setEditingMode(false);

                if (hdfNavireEtranger.Value == "True")
                    lkbModifier.Visible = false;

                serialization();
            }

            ClientScript.RegisterStartupScript(GetType(), "initializeMap", "initializeMap();", true);

        }

        protected void serialization()
        {
            /* SERIALISATION */
            var programmes = programmeService.getProgrammesAtDate(calProgramme.SelectedDate);
            var creneaux = creneauService.getCreneauxAtDate(calProgramme.SelectedDate);

            var programme = from p in programmes
                             where p.NAVIREID == int.Parse(hdfIdNavire.Value)
                             let c1 = creneauService.getCreneauForProgrammeAndOrder(p.ID, 1)
                             let c2 = creneauService.getCreneauForProgrammeAndOrder(p.ID, 2)
                             let c3 = creneauService.getCreneauForProgrammeAndOrder(p.ID, 3)
                             let c4 = creneauService.getCreneauForProgrammeAndOrder(p.ID, 4)
                             let c5 = creneauService.getCreneauForProgrammeAndOrder(p.ID, 5)
                             select new
                             {
                                 navireId = p.NAVIREID,
                                 cre1 = c1 != null ? new { siteId = c1.SITEID, siteLat = c1.SITE.LATITUDE, siteLng = c1.SITE.LONGITUDE, activiteNom = (c1.ACTIVITE != null ? c1.ACTIVITE.NOM : activiteIndefinie) } : new { siteId = -1, siteLat = 200.0, siteLng = 200.0, activiteNom = "" },
                                 cre2 = c2 != null ? new { siteId = c2.SITEID, siteLat = c2.SITE.LATITUDE, siteLng = c2.SITE.LONGITUDE, activiteNom = (c2.ACTIVITE != null ? c2.ACTIVITE.NOM : activiteIndefinie) } : new { siteId = -1, siteLat = 200.0, siteLng = 200.0, activiteNom = "" },
                                 cre3 = c3 != null ? new { siteId = c3.SITEID, siteLat = c3.SITE.LATITUDE, siteLng = c3.SITE.LONGITUDE, activiteNom = (c3.ACTIVITE != null ? c3.ACTIVITE.NOM : activiteIndefinie) } : new { siteId = -1, siteLat = 200.0, siteLng = 200.0, activiteNom = "" },
                                 cre4 = c4 != null ? new { siteId = c4.SITEID, siteLat = c4.SITE.LATITUDE, siteLng = c4.SITE.LONGITUDE, activiteNom = (c4.ACTIVITE != null ? c4.ACTIVITE.NOM : activiteIndefinie) } : new { siteId = -1, siteLat = 200.0, siteLng = 200.0, activiteNom = "" },
                                 cre5 = c5 != null ? new { siteId = c5.SITEID, siteLat = c5.SITE.LATITUDE, siteLng = c5.SITE.LONGITUDE, activiteNom = (c5.ACTIVITE != null ? c5.ACTIVITE.NOM : activiteIndefinie) } : new { siteId = -1, siteLat = 200.0, siteLng = 200.0, activiteNom = "" }
                             };


            var sites = from s in siteService.getAllSites()
                        select new
                        {
                            id = s.ID,
                            nom = s.NOM,
                            lat = s.LATITUDE,
                            lng = s.LONGITUDE,
                            /*activites = from a in activiteService.getActivitesOnSite(s.ID)
                                        select new { nom = a.NOM },
                            programmes = from p in programmes
                                         where p.cre1.siteId == s.ID ||
                                               p.cre2.siteId == s.ID ||
                                               p.cre3.siteId == s.ID ||
                                               p.cre4.siteId == s.ID ||
                                               p.cre5.siteId == s.ID
                                         select p*/
                            nbBateaux = (from c in creneaux
                                         where c.SITEID == s.ID
                                         select c).Count()

                        };

            serializer = new System.Web.Script.Serialization.JavaScriptSerializer();

            hdfSerializedSites.Value = serializer.Serialize(sites);
            hdfProgramme.Value = serializer.Serialize(programme);
        }

        protected string getActivites()
        {
            int siteId = int.Parse(hdfClickedSiteId.Value);
            var activites = from a in activiteService.getActivitesOnSite(siteId)
                            select new { nom = a.NOM };

            return serializer.Serialize(activites);
        }

        protected void calProgramme_SelectionChanged(object sender, EventArgs e)
        {
            lblDateProgramme.Text = calProgramme.SelectedDate.ToString("dd/MM/yy");
            hdfJour.Value = calProgramme.SelectedDate.Day.ToString();
            hdfMois.Value = calProgramme.SelectedDate.Month.ToString();
            hdfAnnee.Value = calProgramme.SelectedDate.Year.ToString();

            setProgramme();

            setEditingMode(false);

            serialization();
        }

        protected void btnModifier_Click(object sender, EventArgs e)
        {
            /*shouldBeInEditingMode = !shouldBeInEditingMode;
            //lblDateCourante.Text = lblDateCourante.Text + shouldBeInEditingMode.ToString();
            setEditingMode(shouldBeInEditingMode);*/

            setEditingMode(true);
        }

        protected void btnValider_Click(object sender, EventArgs e)
        {
            setReadProgramme();

            saveProgramme();

            setEditingMode(false);

            serialization();
        }

        protected void btnAnnuler_Click(object sender, EventArgs e)
        {
            setEditProgramme();

            setEditingMode(false);
        }

        protected void setEditingMode(bool editingMode)
        {
            for (int i = 1; i <= 5; i++)
            {
                Control fatherControl = olProgramme.FindControl("li" + i);

                Control hSite = fatherControl.FindControl("hSite" + i);
                hSite.Visible = !editingMode;

                Control pActivite = fatherControl.FindControl("pActivite" + i);
                pActivite.Visible = !editingMode;

                Control ddlModifierSite = fatherControl.FindControl("ddlModifierSite" + i);
                ddlModifierSite.Visible = editingMode;

                Control ddlModifierActivite = fatherControl.FindControl("ddlModifierActivite" + i);
                ddlModifierActivite.Visible = editingMode;
            }

            if (editingMode)
            {
                lblValiderOuAnnuler.Visible = true;
                lkbModifier.Visible = false;
            }
            else
            {
                lblValiderOuAnnuler.Visible = false;
                lkbModifier.Visible = true;
            }


            hdfEditingMode.Value = editingMode.ToString();
        }

        protected void lkbChangerNavire_Click(object sender, EventArgs e)
        {
            lblNomNavire.Visible = false;
            lkbChangerNavire.Visible = false;
        }

        protected void ddlModifierSite_SelectedIndexChanged(object sender, EventArgs e)
        {
            DropDownList ddlModifierSite = (DropDownList)sender;
            int ordre = int.Parse(ddlModifierSite.ID.Substring(ddlModifierSite.ID.Length - 1));

            Control fatherControl = olProgramme.FindControl("li" + ordre);
            DropDownList ddlModifierActivite = (DropDownList)fatherControl.FindControl("ddlModifierActivite" + ordre);
            ListItem lastSelectedItem = ddlModifierActivite.SelectedItem;

            setDdlModifierActiviteDataSource(ddlModifierActivite, ddlModifierSite);

            if (ddlModifierActivite.Items.Contains(lastSelectedItem))
            {
                ddlModifierActivite.SelectedValue = lastSelectedItem.Value;
            }
            else
            {
                ddlModifierActivite.SelectedValue = activiteIndefinie;
            }


            fatherControl = olProgramme.FindControl("li1");
            DropDownList ddlModifierSite1 = (DropDownList)fatherControl.FindControl("ddlModifierSite" + 1);
            hdfSelectedValues.Value = ddlModifierSite1.SelectedValue;

            for (int i = 2; i <= 5; i++)
            {
                fatherControl = olProgramme.FindControl("li" + i);

                DropDownList ddlModifierSiteX = (DropDownList)fatherControl.FindControl("ddlModifierSite" + i);

                hdfSelectedValues.Value = String.Join("|", new String[] { hdfSelectedValues.Value, ddlModifierSiteX.SelectedValue });
            }


            setDdlModifierSitesDataSources();


            String[] selectedValues = hdfSelectedValues.Value.Split('|');

            for (int i = 1; i <= selectedValues.Length; i++)
            {
                fatherControl = olProgramme.FindControl("li" + i);
                DropDownList ddlModifierSiteCourant = (DropDownList)fatherControl.FindControl("ddlModifierSite" + i);
                ddlModifierSiteCourant.SelectedValue = selectedValues[i - 1];

                DropDownList ddlModifierSitePrecedent = null;
                int indexItemPrecedent = -1;
                if (i > 1 && ddlModifierSiteCourant.SelectedValue != siteIndefini)
                {
                    fatherControl = olProgramme.FindControl("li" + (i - 1));
                    ddlModifierSitePrecedent = (DropDownList)fatherControl.FindControl("ddlModifierSite" + (i - 1));
                    indexItemPrecedent = ddlModifierSitePrecedent.Items.IndexOf(ddlModifierSiteCourant.Items.FindByValue(ddlModifierSiteCourant.SelectedValue));

                    if (indexItemPrecedent != -1)
                    {
                        ddlModifierSitePrecedent.Items.RemoveAt(indexItemPrecedent);
                    }
                }

                DropDownList ddlModifierSiteSuivant = null;
                int indexItemSuivant = -1;
                if (i < 5 && ddlModifierSiteCourant.SelectedValue != siteIndefini)
                {
                    fatherControl = olProgramme.FindControl("li" + (i + 1));
                    ddlModifierSiteSuivant = (DropDownList)fatherControl.FindControl("ddlModifierSite" + (i + 1));
                    indexItemSuivant = ddlModifierSiteSuivant.Items.IndexOf(ddlModifierSiteCourant.Items.FindByValue(ddlModifierSiteCourant.SelectedValue));

                    if (indexItemSuivant != -1)
                    {
                        ddlModifierSiteSuivant.Items.RemoveAt(indexItemSuivant);
                    }
                }
            }

            

            /*Bitmap objBitmap;
            Graphics objGraphics;

            objBitmap = new Bitmap(1, 1);
            objGraphics = Graphics.FromImage(objBitmap);

            SizeF stringSize = objGraphics.MeasureString(ddlModifierSite.SelectedItem.Text, new Font("Sans-serif", 12));

            objBitmap.Dispose();
            objGraphics.Dispose();

            ddlModifierSite.Width = new Unit(stringSize.Width);*/
        }

        protected void ddlModifierActivite_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        protected void setEditProgramme() 
        {
            setDdlModifierSitesDataSources();

            for (int i = 1; i <= 5; i++)
            {
                Control fatherControl = olProgramme.FindControl("li" + i);

                DropDownList ddlModifierSite = (DropDownList)fatherControl.FindControl("ddlModifierSite" + i);
                DropDownList ddlModifierActivite = (DropDownList)fatherControl.FindControl("ddlModifierActivite" + i);
                HiddenField hdfIdCreneau = (HiddenField)fatherControl.FindControl("hdfIdCreneau" + i);

                if (hdfIdProgramme.Value == "-1")
                {
                    ddlModifierSite.SelectedValue = siteIndefini;

                    setDdlModifierActiviteDataSource(ddlModifierActivite, ddlModifierSite);

                    ddlModifierActivite.SelectedValue = activiteIndefinie;

                    hdfIdCreneau.Value = "-1";
                }
                else
                {
                    CRENEAU creneau = creneauService.getCreneauForProgrammeAndOrder(int.Parse(hdfIdProgramme.Value), i);
                    if (creneau == null)
                    {
                        ddlModifierSite.SelectedValue = siteIndefini;

                        setDdlModifierActiviteDataSource(ddlModifierActivite, ddlModifierSite);

                        ddlModifierActivite.SelectedValue = activiteIndefinie;

                        hdfIdCreneau.Value = "-1";
                    }
                    else
                    {
                        ddlModifierSite.SelectedValue = siteService.getSiteById(creneau.SITEID).ID.ToString();

                        setDdlModifierActiviteDataSource(ddlModifierActivite, ddlModifierSite);

                        if (creneau.ACTIVITEID == null)
                            ddlModifierActivite.SelectedValue = activiteIndefinie;
                        else
                            ddlModifierActivite.SelectedValue = activiteService.getActiviteById((int)creneau.ACTIVITEID).ID.ToString();

                        hdfIdCreneau.Value = "" + creneau.ID;
                    }
                }
            }
        }

        protected void setDdlModifierSitesDataSources()
        {
            for (int i = 1; i <= 5; i++)
            {
                Control fatherControl = olProgramme.FindControl("li" + i);
                DropDownList ddlModifierSite = (DropDownList)fatherControl.FindControl("ddlModifierSite" + i);

                ddlModifierSite.Items.Clear();
                ddlModifierSite.SelectedValue = null;

                ddlModifierSite.DataSource = siteService.getSitesForProgrammeAndOrderAtDate(int.Parse(hdfIdProgramme.Value), i, calProgramme.SelectedDate);
                ddlModifierSite.DataValueField = "ID";
                ddlModifierSite.DataTextField = "NOM";
                ddlModifierSite.DataBind();
                ddlModifierSite.Items.Add(siteIndefini);
            }
        }

        protected void setDdlModifierActiviteDataSource(DropDownList ddlModifierActivite, DropDownList ddlModifierSite)
        {
            ddlModifierActivite.Items.Clear();
            ddlModifierActivite.SelectedValue = null;

            string siteId = ddlModifierSite.SelectedValue;
            if (siteId != siteIndefini)
            {
                ddlModifierActivite.DataSource = activiteService.getActivitesOnSite(int.Parse(siteId));
                ddlModifierActivite.DataValueField = "ID";
                ddlModifierActivite.DataTextField = "NOM";
                ddlModifierActivite.DataBind();
            }

            ddlModifierActivite.Items.Add(activiteIndefinie);
        }

        protected void setReadProgramme() {
            hSite1.InnerText = ddlModifierSite1.SelectedItem.Text;
            pActivite1.InnerText = ddlModifierActivite1.SelectedItem.Text;

            hSite2.InnerText = ddlModifierSite2.SelectedItem.Text;
            pActivite2.InnerText = ddlModifierActivite2.SelectedItem.Text;

            hSite3.InnerText = ddlModifierSite3.SelectedItem.Text;
            pActivite3.InnerText = ddlModifierActivite3.SelectedItem.Text;

            hSite4.InnerText = ddlModifierSite4.SelectedItem.Text;
            pActivite4.InnerText = ddlModifierActivite4.SelectedItem.Text;

            hSite5.InnerText = ddlModifierSite5.SelectedItem.Text;
            pActivite5.InnerText = ddlModifierActivite5.SelectedItem.Text;
        }


        protected void setProgramme()
        {
            PROGRAMME programmeCourant = programmeService.getProgrammeForNavireAtDate(int.Parse(hdfIdNavire.Value), calProgramme.SelectedDate);
            if (programmeCourant == null)
                hdfIdProgramme.Value = "-1";
            else
                hdfIdProgramme.Value = programmeCourant.ID.ToString();

            setEditProgramme();
            setReadProgramme();
        }

        protected void saveProgramme()
        {
            if (hdfIdProgramme.Value == "-1")
            {
                hdfIdProgramme.Value = programmeService.createProgramme(int.Parse(hdfIdNavire.Value), calProgramme.SelectedDate).ID.ToString();
            }

            for (int i = 1; i <= 5; i++)
            {
                Control fatherControl = olProgramme.FindControl("li" + i);

                DropDownList ddlModifierSite = (DropDownList)fatherControl.FindControl("ddlModifierSite" + i);
                DropDownList ddlModifierActivite = (DropDownList)fatherControl.FindControl("ddlModifierActivite" + i);

                string siteId = ddlModifierSite.SelectedValue;
                string activiteId = ddlModifierActivite.SelectedValue;

                HiddenField hdfIdCreneau = (HiddenField)fatherControl.FindControl("hdfIdCreneau" + i);
                int creneauId = int.Parse(hdfIdCreneau.Value);

                if (creneauId == -1)
                {
                    if (siteId != siteIndefini)
                    {
                        CRENEAU newCreneau;

                        if (activiteId != activiteIndefinie)
                        {
                            newCreneau = creneauService.createCreneau(int.Parse(hdfIdProgramme.Value), i, int.Parse(activiteId), int.Parse(siteId));
                        }
                        else
                        {
                            newCreneau = creneauService.createCreneau(int.Parse(hdfIdProgramme.Value), i, -1, int.Parse(siteId));
                        }

                        hdfIdCreneau.Value = newCreneau.ID.ToString();
                    }
                }
                else
                {
                    if (siteId != siteIndefini)
                    {
                        if (activiteId != activiteIndefinie)
                        {
                            creneauService.updateCreneau(creneauId, int.Parse(hdfIdProgramme.Value), i, int.Parse(activiteId), int.Parse(siteId));
                        }
                        else
                        {
                            creneauService.updateCreneau(creneauId, int.Parse(hdfIdProgramme.Value), i, -1, int.Parse(siteId));
                        }
                    }
                    else
                    {
                        creneauService.deleteCreneau(creneauId);
                        hdfIdCreneau.Value = "-1";
                    }
                }
            }
        }

        /*protected void setEditingMode(bool shouldBeInEditingMode)
        {
            if (shouldBeInEditingMode)
            {
                pActivitePetitMatin.Visible = false;
                hSitePetitMatin.Visible = false;
                ddlModifierSitePetitMatin.Visible = true;
                ddlModifierActivitePetitMatin.Visible = true;

                pActiviteMatin.Visible = false;
                hSiteMatin.Visible = false;
                ddlModifierSiteMatin.Visible = true;
                ddlModifierActiviteMatin.Visible = true;

                pActiviteApresMidi.Visible = false;
                hSiteApresMidi.Visible = false;
                ddlModifierSiteApresMidi.Visible = true;
                ddlModifierActiviteApresMidi.Visible = true;

                pActiviteSoiree.Visible = false;
                hSiteSoiree.Visible = false;
                ddlModifierSiteSoiree.Visible = true;
                ddlModifierActiviteSoiree.Visible = true;

                pActiviteNuit.Visible = false;
                hSiteNuit.Visible = false;
                ddlModifierSiteNuit.Visible = true;
                ddlModifierActiviteNuit.Visible = true;
            }
            else
            {
                pActivitePetitMatin.Visible = true;
                hSitePetitMatin.Visible = true;
                ddlModifierSitePetitMatin.Visible = false;
                ddlModifierActivitePetitMatin.Visible = false;

                pActiviteMatin.Visible = true;
                hSiteMatin.Visible = true;
                ddlModifierSiteMatin.Visible = false;
                ddlModifierActiviteMatin.Visible = false;

                pActiviteApresMidi.Visible = true;
                hSiteApresMidi.Visible = true;
                ddlModifierSiteApresMidi.Visible = false;
                ddlModifierActiviteApresMidi.Visible = false;

                pActiviteSoiree.Visible = true;
                hSiteSoiree.Visible = true;
                ddlModifierSiteSoiree.Visible = false;
                ddlModifierActiviteSoiree.Visible = false;

                pActiviteNuit.Visible = true;
                hSiteNuit.Visible = true;
                ddlModifierSiteNuit.Visible = false;
                ddlModifierActiviteNuit.Visible = false;
            }
        }*/
    }
}